package com.semanticweb.webapp.service.impl;

import java.util.ArrayList;
import java.util.Collection;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.semanticweb.webapp.model.ontology.Item;
import com.semanticweb.webapp.ontology.CIDOC;
import com.semanticweb.webapp.ontology.CType;
import com.semanticweb.webapp.ontology.Ont;
import com.semanticweb.webapp.ontology.Query;
import com.semanticweb.webapp.search.ItemSearch;
import com.semanticweb.webapp.service.OntologyService;
import com.semanticweb.webapp.service.RBACService;
import com.semanticweb.webapp.util.InitialItems;

/**
 * Implementation of {@link com.semanticweb.webapp.service.OntologyService}.
 * 
 * @author Srdjan Radulovic
 */
@Service
public class OntologyServiceImpl implements OntologyService {

    private static final Logger LOGGER = LoggerFactory.getLogger(OntologyServiceImpl.class);

    @Autowired
    private RBACService rbacService;

    private ItemSearch search;

    @Override
    public Collection<Item> findItems(final String query) {
        return this.search.search(query);
    }

    @Override
    public String findItemsBySparquelQuery(final String query) {
        final ResultSet result = Ont.quickQuery(query);
        return ResultSetFormatter.asText(result);
        // Ont.defaultQueryPrefixes()
    }

    @Override
    public Item getItemByID(final String id) {
        final Item item = new Item(id);
        item.fromRDF();
        return item;
    }

    @Override
    public Collection<Item> getAllItems() {
        final Query q = new Query();
        final String[] result = q.selectLabel().type("iv", CIDOC.E42.queryValue())
                .connect("iv", CIDOC.P2.queryValue(), CType.INVENTARY_NUMBER.queryValue()).findLabel("iv");

        final Collection<Item> items = new ArrayList<Item>();
        for (final String s : result) {
            final Item item = new Item(s);
            item.fromRDF();
            items.add(item);
        }

        return items;
    }

    @PostConstruct
    public void setup() {
        Ont.initializeOnt();
        this.search = new ItemSearch();

        this.search.clearIndex();

        createItem(InitialItems.createItemA());

        // createItem(InitialItems.createItemB());
        // createItem(InitialItems.createItemC());
    }

    @Override
    public void createItem(final Item item) {
        // LOGGER.debug("Item with author " + item.getAuthor().getValue() + " is created!");
        item.toRDF();
        this.search.index(item);
        Ont.getOntology().saveModel();
        rbacService.addNewObject(item.getInventaryNumber().getValue());
    }
}
